// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

const db = cloud.database()
const _ = db.command

// 云函数入口函数
exports.main = async (event, context) => {
  const roomId = event.room
  
  try {
    await db.runTransaction(async transaction => {
      // 重置 game_card 表数据
      await transaction.collection("game_card").where({
        room: roomId,
        processing: true
      }).update({ 
        data: {
          processing: false
        }
      })
      
      // 重置 game_scenes 表数据
      await transaction.collection("game_scenes").where({
        room: roomId,
        processing: _.neq(2)
      }).update({ 
        data: {
          processing: 2
        }
      })
      
      // 重置 user 表数据
      await transaction.collection("user").where({
        room: roomId
      }).update({ 
        data: {
          role: "",
          solve: false,
          status: "ready"
        }
      })

      // 重置 game_info 数据
      await transaction.collection("game_info").where({
        room: roomId,
        round: 0
      }).update({ 
        data: {
          round: 4
        }
      })
    })
  } catch (e) {
    console.log("[云函数] [resetGame] 事务执行失败: ", e)
    return false
  }

  return true
}